package base.utils

import java.io.IOException
import java.io.RandomAccessFile

/**
 * Created by Administrator on 2018/4/24.
 */
class NetSpeedUtils {
    private val mobileRxFile_1 = "/sys/class/net/wlan0/statistics/rx_bytes"//无线总下载量
    private val mobileRxFile_2 = "/sys/class/net/eth0/statistics/rx_bytes"//有线下载总量
    private val mobileTxFile_1 = "/sys/class/net/wlan0/statistics/tx_bytes"//无线总上传量
    private val mobileTxFile_2 = "/sys/class/net/eth0/statistics/tx_bytes"//有线上传总量

    private val LOGGING_TAG = NetSpeedUtils::class.java.simpleName

    fun getMobileRxBytes(): Long {
        return tryBoth(mobileRxFile_1, mobileRxFile_2)
    }

    fun getWriedRxBytes(): Long {
        return tryBoth(mobileRxFile_2, mobileRxFile_2)
    }

    fun getMobileTxBytes(): Long {
        return tryBoth(mobileTxFile_1, mobileTxFile_2)
    }

    fun getWriedTxBytes(): Long {
        return tryBoth(mobileTxFile_2, mobileTxFile_2)
    }

    // Return the number from the first file which exists and contains data
    private fun tryBoth(a: String, b: String): Long {
        return readNumber(a)//num >= 0 ? num : readNumber(b);
    }


    // Returns an ASCII decimal number read from the specified file, -1 on error.
    private fun readNumber(filename: String): Long {
        var f: RandomAccessFile? = null
        try {
            f = RandomAccessFile(filename, "r")
            //            Log.d(LOGGING_TAG, "f.length() = " + f.length());
            val contents = f.readLine()
            if (contents != null && !contents.isEmpty()) {
                return java.lang.Long.parseLong(contents)
            }
        } catch (e: Exception) {
            //            Log.w(LOGGING_TAG, "File not found: " + filename, ffe);
        } finally {
            if (f != null) {
                try {
                    f.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }
        return -1
    }

}